package com.xz.sanitize.serializer;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.xz.sanitize.annotation.NullPolicy;
import com.xz.sanitize.strategy.DefaultValueProvider;

import java.util.List;
import java.util.Objects;

/**
 * 修改属性写入器，以应用空值处理策略和默认值。
 */
public class NullAwareBeanSerializerModifier extends BeanSerializerModifier {
    private final DefaultValueProvider provider;

    public NullAwareBeanSerializerModifier(DefaultValueProvider provider) {
        this.provider = provider;
    }

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
                                                     BeanDescription beanDesc,
                                                     List<BeanPropertyWriter> beanProperties) {
        NullPolicy nullPolicy = beanDesc.getBeanClass().getAnnotation(NullPolicy.class);
        if (Objects.nonNull(nullPolicy) && nullPolicy.value() == NullPolicy.Mode.AllowNull) {
            return beanProperties;
        }
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter bpw = beanProperties.get(i);
            NullPolicy policy = bpw.getMember() != null ? bpw.getMember().getAnnotation(NullPolicy.class) : null;
            if (policy != null && policy.value() == NullPolicy.Mode.AllowNull) {
                continue;
            }
            beanProperties.set(i, new DefaultingPropertyWriter(bpw, provider));
        }
        return beanProperties;
    }
}
